package com.intellekt.ecert.importacion.action;

import static org.apache.commons.lang.StringUtils.isBlank;
import static org.apache.commons.lang.StringUtils.isNotBlank;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.client.WebServiceIOException;

import com.intellekt.ecert.domain.SuperAction;
import com.intellekt.ecert.sps.SPSAuthentication;
import com.intellekt.ecert.sps.SPSCertificateType;
import com.intellekt.ecert.sps.SPSConsignmentItem;
import com.intellekt.ecert.sps.SPSTradeLineItemType;
import com.intellekt.ecert.sps.TextType;
import com.intellekt.ecert.ws.client.Client;

public class ImportacionAsyncAction extends SuperAction {

	/**
     * 
     */
	private static final long serialVersionUID = -5836052371448966636L;

	private static final Logger log = Logger.getLogger(ImportacionAsyncAction.class);

	public static SimpleDateFormat getSDF() throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
		sdf.setLenient(false);
		return sdf;
	}

	static final String DIV_FECHA = "div.fecha";

	@Autowired
	private Client wsClient;

	private String jsonrecords;
	private String from;
	private String to;
	private String idCert;

	public String validar() throws Exception {
		if (log.isInfoEnabled()) {
			log.info("validar... ");
			log.info("from ... " + from);
			log.info("to... " + to);
			log.info("idCert... " + idCert);
		}
		JSONObject messages = new JSONObject();
		JSONArray divs = new JSONArray();
		JSONArray alerts = new JSONArray();
		boolean success = true;
		String msgError = null;

		try {

			if (isBlank(idCert)) {

				msgError = "";
				if (isBlank(to)) {
					success = false;
					msgError = "Introduza la fecha final";
					divs.add(getDivYMensaje(DIV_FECHA, msgError));
				}

				msgError = "";
				if (isBlank(from)) {
					success = false;
					msgError = "Introduzca la fecha inicial";
					divs.add(getDivYMensaje(DIV_FECHA, msgError));
				}

				if (isNotBlank(from) && isNotBlank(to)) {

					Date fromDate = getSDF().parse(from);
					Date toDate = getSDF().parse(to);

					int days = Days.daysBetween(new DateTime(fromDate), new DateTime(toDate)).getDays();

					msgError = "";
					if (fromDate.after(toDate)) {
						success = false;
						msgError = "Rango de fecha invalido";
						divs.add(getDivYMensaje(DIV_FECHA, msgError));
					}
					msgError = "";
					if (days > 30) {
						success = false;
						msgError = getText("certificados.importacion.rango");
						divs.add(getDivYMensaje(DIV_FECHA, msgError));
					}

				}
			}

		} catch (Exception e) {
			log.error("error", e);
			success = false;
			messages.put(JSON_EXCEPTION, e.toString());
		} finally {
			messages.put(JSON_DIVS, divs);
			messages.put(JSON_ALERTS, alerts);
			messages.put(JSON_SUCCESS, success);
			if (log.isDebugEnabled()) {
				log.debug(messages.toString(1));
			}
			streamIt(messages);
		}
		return STREAM;
	}

	public String busqueda() throws Exception {
		boolean success = true;
		JSONObject messages = new JSONObject();
		JSONArray divs = new JSONArray();
		JSONArray alerts = new JSONArray();
		try {
			Map<Object, Object> resultSet = new HashMap<Object, Object>();
			List<Map<Object, Object>> mapResult = new ArrayList<Map<Object, Object>>();

			List<SPSCertificateType> list = new ArrayList<SPSCertificateType>();

			if (isNotBlank(idCert)) {
				SPSCertificateType x = wsClient.getCertificate(idCert);
				if (x != null) {
					list.add(x);
				} else {
					x = new SPSCertificateType();
				}
			} else {
				list = wsClient.getCertificatesByInfo(from, to);
			}

			if (list != null) {
				for (SPSCertificateType tmp : list) {
					Map<Object, Object> map = new HashMap<Object, Object>();

					map.put("folio", tmp.getSPSExchangedDocument().getID());
					map.put("status", tmp.getSPSExchangedDocument().getStatusCode());
					map.put("consignor", tmp.getSPSConsignment().getConsignorSPSParty().getName());
					map.put("consignee", tmp.getSPSConsignment().getConsigneeSPSParty().getName());
					mapResult.add(map);
				}
			}
			resultSet.put("Result", mapResult);
			messages.put("ResultSet", resultSet);

		} catch (WebServiceIOException e) {
			log.error("error", e);
			success = false;
			messages.put(JSON_EXCEPTION, getText("certificados.excepcion.conexion"));
		} catch (Exception e) {
			log.error("error", e);
			success = false;
			messages.put(JSON_EXCEPTION, e.toString());
		} finally {
			messages.put(JSON_DIVS, divs);
			messages.put(JSON_ALERTS, alerts);
			messages.put(JSON_SUCCESS, success);
			if (log.isDebugEnabled()) {
				log.debug(messages.toString(1));
			}
			streamIt(messages);
		}

		return STREAM;
	}

	public String mercancia() throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("mercancia " + idCert);
		}
		boolean success = true;
		JSONObject messages = new JSONObject();
		JSONArray divs = new JSONArray();
		JSONArray alerts = new JSONArray();
		try {
			Map<Object, Object> resultSet = new HashMap<Object, Object>();
			List<Map<Object, Object>> mapResult = new ArrayList<Map<Object, Object>>();

			SPSCertificateType cert = wsClient.getCertificate(idCert);

			if (cert != null) {
				List<SPSConsignmentItem> list = cert.getSPSConsignment().getIncludedSPSConsignmentItems();

				for (SPSConsignmentItem tmp : list) {
					SPSTradeLineItemType item = tmp.getIncludedSPSTradeLineItems().get(0);
					StringBuffer stb = new StringBuffer();

					Map<Object, Object> map = new HashMap<Object, Object>();
					log.debug("sequence " + item.getSequenceNumeric());
					map.put("sequence", item.getSequenceNumeric());

					for (String x : item.getDescriptions()) {
						stb.append(x.toString());
					}
					map.put("description", stb.toString());
					map.put("commonname", item.getCommonNames());

					stb = new StringBuffer();
					for (String x : item.getScientificNames()) {
						stb.append(x.toString());
					}
					map.put("scientificname", stb.toString());

					mapResult.add(map);
				}

				resultSet.put("Result", mapResult);
				messages.put("ResultSet", resultSet);
			} else {
				throw new Exception("no se encontraron mercancias");
			}
		} catch (WebServiceIOException e) {
			log.error("error", e);
			success = false;
			messages.put(JSON_EXCEPTION, "No se pudo conectar al WS de EUU, intentelo mas tarde");
		} catch (Exception e) {
			log.error("error", e);
			success = false;
			messages.put(JSON_EXCEPTION, e.toString());
		} finally {
			messages.put(JSON_DIVS, divs);
			messages.put(JSON_ALERTS, alerts);
			messages.put(JSON_SUCCESS, success);
			if (log.isDebugEnabled()) {
				log.debug(messages.toString(1));
			}
			streamIt(messages);
		}

		return STREAM;
	}

	public String detalleCertificado() throws Exception {
		boolean success = true;
		JSONObject messages = new JSONObject();
		JSONArray divs = new JSONArray();
		JSONArray alerts = new JSONArray();
		try {
			Map<Object, Object> resultSet = new HashMap<Object, Object>();
			List<Map<Object, Object>> mapResult = new ArrayList<Map<Object, Object>>();
			StringBuffer stb = new StringBuffer();
			SPSCertificateType cert = wsClient.getCertificate(idCert);

			if (cert != null) {
				List<SPSConsignmentItem> list = cert.getSPSConsignment().getIncludedSPSConsignmentItems();
				Map<Object, Object> map = new HashMap<Object, Object>();

				for (TextType x : cert.getSPSExchangedDocument().getNames()) {
					stb.append(x.getValue());
				}
				
				map.put("SPSExDocIssuerSPSPartyName", cert.getSPSExchangedDocument().getIssuerSPSParty().getName());
				
				
				map.put("tipoCertificado", stb.toString());
				map.put("noCert", cert.getSPSExchangedDocument().getID());
				map.put("date", cert.getSPSExchangedDocument().getIssueDateTime().toString());

				map.put("authDateTime", cert.getSPSExchangedDocument().getIssueDateTime().toString());

				stb = new StringBuffer();
				for (SPSAuthentication x : cert.getSPSExchangedDocument().getSignatorySPSAuthentications()) {
					for (String y : x.getIssueSPSLocation().getNames()) {
						stb.append(y);
					}
				}
				map.put("issuelocation", stb.toString());

				mapResult.add(map);

				resultSet.put("Result", mapResult);
				messages.put("ResultSet", resultSet);
			} else {
				throw new Exception("no se encontraron mercancias");
			}

		} catch (Exception e) {
			log.error("error", e);
			success = false;
			messages.put(JSON_EXCEPTION, e.toString());
		} finally {
			messages.put(JSON_DIVS, divs);
			messages.put(JSON_ALERTS, alerts);
			messages.put(JSON_SUCCESS, success);
			if (log.isDebugEnabled()) {
				log.debug(messages.toString(1));
			}
			streamIt(messages);
		}

		return STREAM;
	}

	public final String getJsonrecords() {
		return jsonrecords;
	}

	public final void setJsonrecords(String jsonrecords) {
		this.jsonrecords = jsonrecords;
	}

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	public String getTo() {
		return to;
	}

	public void setTo(String to) {
		this.to = to;
	}

	public void setIdCert(String idCert) {
		this.idCert = idCert;
	}

	public String getIdCert() {
		return idCert;
	}

}
